package com.kgcx.common.converter;

import com.kgcx.common.constant.Cons;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.convert.converter.Converter;
import org.springframework.lang.Nullable;

import java.sql.Timestamp;
import java.text.ParseException;

//@Component
public class TimestampConverter implements Converter<String, Timestamp> {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Nullable
    @Override
    public Timestamp convert(String source) {
        Timestamp timestamp = null;
        try {
            timestamp = Timestamp.from(DateUtils.parseDate(source,
                    Cons.DATE_FORMAT_YYYYMMDDHHMMSSSSS,
                    Cons.DATE_FORMAT_YYYYMMDDHHMMSS,
                    Cons.DATE_FORMAT_YYYY_MM_DD_HH_MM_SS,
                    Cons.DATE_FORMAT_YYYY_MM_DD_HH_MM_SS_SSS
            ).toInstant());
        } catch (ParseException e) {
            log.error("时间转换失败", e);
        }
        if (null == timestamp) {
            try {
                timestamp = new Timestamp(Long.valueOf(source));
            } catch (NumberFormatException e) {
                log.error("时间转换失败", e);
            }
        }
        if (null == timestamp) {
            try {
                timestamp = Timestamp.valueOf(source);
            } catch (IllegalArgumentException e) {
                log.error("时间转换失败", e);
            }
        }
        if (null == timestamp) {
            throw new IllegalArgumentException("时间转换失败");
        }
        return timestamp;
    }
}
